package com.lut.edu.apm.payCenter.pay;

import com.alibaba.fastjson.JSONObject;
import com.lut.edu.apm.payCenter.message.AliMessage;
import com.lut.edu.apm.payCenter.util.SnowFlake;
import com.lut.edu.apm.webCenter.pojo.UserInfo;
import com.lut.edu.apm.webCenter.service.UserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Zhao Suzhen
 * @date `2024/4/15`
 */
@RestController
@RequestMapping("/message")
public class MessageController {

    private final Logger logger = LoggerFactory.getLogger(MessageController.class);
    @Autowired
    AliMessage aliMessage;

    @Autowired
    UserInfoService userInfoService;

    @GetMapping("sendLoginCode")
    @ResponseBody
    public String sendLoginCode(@RequestParam("phoneNumber") String phone) throws Exception {
        boolean status = false;
        String log;
        if (userInfoService.isUserLogin(phone)) {
            status = aliMessage.sendRegistrationVerificationCode(phone);
            log = "向%s发送登录短信%s";
        } else {
            status = aliMessage.sendLoginVerificationCode(phone);
            log = "向%s发送注册短信%s";
        }
        Map<String, Object> result = new HashMap<>();
        if (status) {
            result.put("isSuccess", 200);
            logger.info(String.format(log,phone,"成功"));
        } else {
            result.put("isSuccess", 401);
            logger.info(String.format(log,phone,"失败"));
        }
        return JSONObject.toJSONString(result);
    }

    @GetMapping("verifyCode")
    @ResponseBody
    public String verifyCode(@RequestParam("phoneNumber") String phone, @RequestParam("code") String code) throws Exception {
        boolean status = aliMessage.verifyVerificationCode(phone, code);
        Map<String, Object> result = new HashMap<>();
        String log = "验证短信：%s,验证%s";
        if (status) {
            if (!userInfoService.isUserLogin(phone)) {
                UserInfo userInfo = new UserInfo();
                userInfo.setUserId(new SnowFlake(0, 0).nextId());
                userInfo.setPhoneNumber(phone);
                userInfo.setSex("-1");
                userInfo.setUserStatus("U");
                userInfo.setUserPoints(0);
                userInfoService.save(userInfo);
            }
            result.put("isSuccess", 200);
            result.put("userId", userInfoService.queryInfoByPhone(phone).getUserId());
            logger.info(String.format(log,phone,"成功"));
        } else {
            result.put("isSuccess", 401);
            logger.info(String.format(log,phone,"失败"));
        }
        return JSONObject.toJSONString(result);
    }
}
